package com.fc.hkx.shiro.filter;

import com.fc.hkx.utils.R;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import static com.fc.hkx.utils.JsonUtils.sendJSON;
import static com.fc.hkx.utils.ShiroUtils.isAjax;

/**
 * Created by Sunny on 2017-08-24.
 */
public class MyLogoutFilter extends LogoutFilter {
    private static final Logger log = LoggerFactory.getLogger(MyLogoutFilter.class);
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        String redirectUrl = getRedirectUrl(request, response, subject);
        //try/catch added for SHIRO-298:
        try {
            subject.logout();
        } catch (SessionException ise) {
            log.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
        }
        if (!isAjax(request)) {
            issueRedirect(request, response, redirectUrl);
        } else {
            sendJSON((HttpServletResponse) response, R.ok("登出成功"));
        }
        return false;
    }
}
